package com.msl.debezium.validate;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class PhoneValidate implements ConstraintValidator<Phone, String> {
    private String phoneType;

    @Override
    public void initialize(Phone phone) {
        phoneType = phone.value().name();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(StringUtils.isBlank(value)){
            return true;
        }
        if(PhoneType.MOBILE.name().equals(phoneType)){
            Pattern p = Pattern.compile("1[3,4,5,8]\\d{9}");
            Matcher m = p.matcher(value);
            return m.matches();
        }else{
            String regex1 = "[0-9]{3,4}[-][0-9]{8}";
            String regex2 = "\\d{7,8}";
            String pattern = value.startsWith("0")?regex1:regex2;
            Pattern p = Pattern.compile(pattern);
            Matcher m = p.matcher(value);
            return m.matches();
        }
    }

    public boolean validate() throws Exception{

        return true;
    }
}
